package ${package}.controller;

import ${package}.utils.Result;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Base64Utils;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 公共接口类
 *
 * @author ${author}
 * @since ${date}
 */
@Api(tags = "公共接口类")
@RestController
@AllArgsConstructor
@RequestMapping("/common")
public class CommonController {

    /**
     * 验证码 redis key
     */
    private static final String CAPTCHA_CODE_KEY = "captcha_codes:";

    /**
     * 验证码有效期（分钟）
     */
    public static final Integer CAPTCHA_EXPIRATION = 2;

    private final StringRedisTemplate redisTemplate;

    private final DefaultKaptcha defaultKaptcha;

    @GetMapping("/captcha")
    @ApiOperation(value = "生成验证码")
    public Result<Map<String, Object>> createCaptcha() {
        Map<String, Object> resMap = new HashMap<>(4);
        String uuid = UUID.randomUUID().toString();
        String verifyKey = CAPTCHA_CODE_KEY + uuid;
        String capText = defaultKaptcha.createText();
        BufferedImage image = defaultKaptcha.createImage(capText);
        //写入redis
        redisTemplate.opsForValue().set(verifyKey, capText, CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        //转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        resMap.put("uuid", uuid);
        byte[] encode = Base64Utils.encode(os.toByteArray());
        resMap.put("image", new String(encode, StandardCharsets.UTF_8));
        return Result.ok(resMap);
    }
}
